﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using TeamWorkGH.NewWindow;
using TeamWorkGH.ServiceReference;
using TeamWorkGH.Utils;

namespace TeamWorkGH
{
    /// <summary>
    /// Project.xaml 的交互逻辑
    /// </summary>
    public partial class ProjectWindow : Window
    {
        UserDTO user;
        GitHubServiceClient client;
        ProjectDTO project;

        public ProjectWindow(string userName, int projectId)
        {
            InitializeComponent();

            client = new GitHubServiceClient();
            this.user = client.FindUserByUserName(userName);
            this.project = client.FindProjectById(projectId);
            this.UserName.Text = userName;
            

            NameAndProjectName.Text = user.UserName + '/' + project.ProjectName;
            CommentList.Items.Add("UserName\tTime\tComment");
            foreach (var item in client.GetAllCommentsByProjectId(project.ProjectId))
            {
                CommentList.Items.Add(item.UserName + '\t' + item.CommentTime.ToString() + '\t' +item.Comment);
            }

            CommitMsg.Text += " " + client.GetCommitNumByProjectId(project.ProjectId).ToString();
            PullRequestMsg.Text += "" + client.GetRequestNumByProjectId(project.ProjectId).ToString();


            
            string dir = client.GetProjectFilesDirectoryByProjectId(projectId);
            if (dir != "" && dir != null)
            {
                List<PropertyNodeItem> nodes = new List<PropertyNodeItem>();
                nodes.Add(this.ShowView(dir));
                this.tree.ItemsSource = nodes;
                client.DeleteFileAfterGetDirectory(dir);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Shutdown();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count > 0)
            {
                Login login = new Login();
                int itemName = comboBox1.SelectedIndex;
                switch (itemName)
                {
                    case 1: login.Show(); this.Close(); break;
                    default:
                        break;
                }
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Commits commits = new Commits(project.ProjectId, user.UserName);
            commits.Show();
            this.Close();
        }

        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mainWindow = new MainWindow(user.UserName);
            mainWindow.Show();
            this.Close();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            PullRequest pullRequest = new PullRequest(user.UserName, project.ProjectId);
            pullRequest.Show();
            this.Close();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void TextBlock_MouseLeftButtonDown_2(object sender, MouseButtonEventArgs e)
        {
            Marketplace marketplace = new Marketplace(user.UserName);
            marketplace.Show();
            this.Close();
        }

        private void addComment_Click(object sender, RoutedEventArgs e)
        {
            if (commentTextbox.Text=="")
            {
                System.Windows.MessageBox.Show("评论不能为空");
            }
            else
            {
                client.AddCommentsByProjectId(project.ProjectId, user.UserName, commentTextbox.Text);
                CommentList.Items.Add(user.UserName + '\t' + DateTime.Now.ToString() + '\t' + commentTextbox.Text);
            }
        }

        private void return_Click(object sender, RoutedEventArgs e)
        {
            MainWindow mainWindow = new MainWindow(user.UserName);
            mainWindow.Show();
            this.Close();

        }

        private void Fork_Click(object sender, RoutedEventArgs e)
        {
            if (user.UserName != project.Owner)
            {
                client.ForkByProjectIdAndUserName(user.UserName, project.ProjectId);
            }
            else
            {
                System.Windows.MessageBox.Show("项目拥有者不能Fork本项目");
            }
        }

        private void down_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.ShowDialog();
            if (string.IsNullOrEmpty(folderBrowser.SelectedPath))
            {
                System.Windows.MessageBox.Show(this, "文件夹路径不能为空", "提示");
            }
            else
            {
                File.Create(Path.Combine(folderBrowser.SelectedPath, Path.GetFileName(project.CurrentUrl))).Close();
                UpAndDownloadFiles.DownloadStream(client.GetProjectFilesById(project.ProjectId), 
                    Path.Combine(folderBrowser.SelectedPath, Path.GetFileName(project.CurrentUrl)));
                System.Windows.MessageBox.Show("下载成功");
            }
        }

        private void UpCommit_Click(object sender, RoutedEventArgs e)
        {
            if (IsAdmin.IsAdminstrator(user.UserName, project.Owner))
            {
                NewCommitWindow newCommit = new NewCommitWindow(user.UserName, project.ProjectId, this);
                newCommit.Show();
            }
            else
            {
                System.Windows.MessageBox.Show("非管理员不能添加修改项目");
            }
        }

        private void UpRequest_Click(object sender, RoutedEventArgs e)
        {
            NewRequestWindow newRequestWindow = new NewRequestWindow(user.UserName, project.ProjectId, this);
            newRequestWindow.Show();
        }

        public PropertyNodeItem ShowView(string path)
        {
            DirectoryInfo info = new DirectoryInfo(path);
            FileInfo[] fileInfo = info.GetFiles();
            DirectoryInfo[] directories = info.GetDirectories();

            string[] paths = path.Split('\\');
            PropertyNodeItem root = new PropertyNodeItem()
            {
                FileName = paths[paths.Length - 1]
            };

            //设置图标
            if (Directory.Exists(path))
            {
                string iconPath = AppDomain.CurrentDomain.BaseDirectory;
                iconPath += "Icon\\directory.png";
                root.Icon = iconPath;
            }
            else
            {
                string iconPath = AppDomain.CurrentDomain.BaseDirectory;
                iconPath += "Icon\\file.png";
                root.Icon = iconPath;
            }


            foreach (var item in directories)
            {
                root.Children.Add(this.ShowView(item.FullName));
            }

            foreach (var item in fileInfo)
            {
                PropertyNodeItem childNode = new PropertyNodeItem() { FileName = Path.GetFileName(item.FullName) };
                string iconPath = AppDomain.CurrentDomain.BaseDirectory;
                iconPath += "Icon\\file.png";
                childNode.Icon = iconPath;

                root.Children.Add(childNode);
            }

            return root;
        }
    }

    public class PropertyNodeItem
    {
        public string Icon { set; get; }
        public string FileName { set; get; }
        public List<PropertyNodeItem> Children { set; get; }

        public PropertyNodeItem()
        {
            this.Children = new List<PropertyNodeItem>();
        }
    }
}
